package org.apache.ws.secpolicy11.builders;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.Constants;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.builders.AssertionBuilder;
import org.apache.ws.secpolicy.SP11Constants;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.secpolicy.model.OpenIDToken;

public class OpenIDTokenBuilder implements AssertionBuilder{

	public Assertion build(OMElement element, AssertionBuilderFactory factory) throws IllegalArgumentException {
		OpenIDToken openIDToken = new OpenIDToken(SPConstants.SP_V11);
		
		OMAttribute attribute = element.getAttribute(SP11Constants.INCLUDE_TOKEN); 
		if(attribute != null){
			int inclusion = SP11Constants.getInclusionFromAttributeValue(attribute.getAttributeValue());
			openIDToken.setInclusion(inclusion);			
		}
		
		OMAttribute isOptional = element.getAttribute(Constants.Q_ELEM_OPTIONAL_ATTR);
		if (isOptional != null) {
			openIDToken.setOptional(Boolean.valueOf(isOptional.getAttributeValue())
					.booleanValue());
		}
		
		OMElement policyElement = element.getFirstElement();
        if (policyElement != null && policyElement.getQName().equals(org.apache.neethi.Constants.Q_ELEM_POLICY)) {
            Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
            policy = (Policy) policy.normalize(false);
            for (Iterator iterator = policy.getAlternatives(); iterator.hasNext();) {
                processAlternative((List) iterator.next(), openIDToken);
                break;
            }            
        }
		return openIDToken;
	}

	public QName[] getKnownElements() {
		return new QName[] {SP11Constants.OPENID_TOKEN};
	}

	private void processAlternative(List assertions, OpenIDToken parent) {
        
        for (Iterator iterator = assertions.iterator(); iterator.hasNext();) {
            Assertion assertion = (Assertion) iterator.next();
            QName qname = assertion.getName();
            
            if (SP11Constants.REQUIRE_DERIVED_KEYS.equals(qname)) {
                parent.setDerivedKeys(true);
            }
        }
    }
}
